﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Microsoft.HomeServer.HomeServerConsoleTab.DuplicationInfo
{
    internal class ShellIcon
    {
        public const int MAX_PATH = 260;

        public const int SHGFI_ICON = 0x00000100;
        public const int SHGFI_SYSICONINDEX = 0x000004000;
        public const int SHGFI_LARGEICON = 0x00000000;
        public const int SHGFI_SMALLICON = 0x00000001;
        public const int SHGFI_OPENICON = 0x00000002;

        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public Int32 iIcon;
            public UInt32 dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_PATH)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }

        [DllImport("shell32.dll", CharSet=CharSet.Unicode)]
        private static extern IntPtr SHGetFileInfo(
            string pszPath,
            UInt32 dwFileAttribuets,
            ref SHFILEINFO psfi,
            UInt32 cbFileInfo,
            UInt32 uFlags
            );

        [DllImport("user32.dll", CharSet=CharSet.Unicode)]
        private static extern UInt32 DestroyIcon(
            IntPtr hIcon
            );

        public static Icon GetIcon(string filename)
        {
            SHFILEINFO info = new SHFILEINFO();
            IntPtr hImageList = SHGetFileInfo(
                filename,
                0,
                ref info,
                (UInt32)Marshal.SizeOf(info),
                SHGFI_ICON | SHGFI_SMALLICON
                );
            if (hImageList == IntPtr.Zero)
            {
                return null;
            }
            try
            {
                Icon tmp = Icon.FromHandle(info.hIcon);
                return new Icon(tmp, tmp.Size);
            }
            finally
            {
                DestroyIcon(info.hIcon);
            }
        }
    }
}
